/*
 * Copyright (C) 2008 CERNET Network Center 
 * dvping/dvmcast/hdvping/hdvmcast series 
 * 
 * Design and coding: 
 *  	Xing Li <xing@cernet.edu.cn> 
 *	Congxiao Bao <congxiao@cernet.edu.cn>
 * 	Jinpeng Jiang <jjp02@mails.tsinghua.edu.cn>
 * 
 * Contributions:
 * 
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 */

#include "dvdest.h"
#include "dvsource.h"
#include <math.h>

IDVDestination::IDVDestination()
{
	thread = NullThread;
	quitThread = false;
}
IDVDestination::~IDVDestination()
{
	Stop();
}
void IDVDestination::SetDVSource(IDVSource* pSource)
{
	this->pSource = pSource;
}
bool IDVDestination::Start()
{
	quitThread = false;
	thread = NullThread;
	return Thread::Create(thread, ThreadDelegate(this, &IDVDestination::DestProc));
}
bool IDVDestination::Stop()
{
	if(thread != NullThread)
	{
		quitThread = true;
		evtThreadQuit.WaitForSignal(5000000);
		if(thread != NullThread)
		{
			Thread::Kill(thread);
			thread = NullThread;
		}
	}
	return true;
}

void* IDVDestination::DestProc(void*)
{
	if(!Init())
		return NULL;
	packet_iterator itpkt = pSource->GetFirstPacket();
	while(!quitThread)
	{
		char* pdata;
		u_int32_t length;
		IPEndPoint ep;
		u_int32_t pkt_left = 0;
		pdata = pSource->GetNextPacket(itpkt, length, ep, pkt_left);

		if(pdata == NULL)
		{
			Thread::Sleep(1000);
		}
		else
		{
			DealPacket(pdata, length, ep);
		}
	}
	pSource->ReleaseIterator(itpkt);
	Cleanup();
	thread = NullThread;
	evtThreadQuit.Signal();
	return NULL;
}
bool IDVDestination::Init()
{
	return true;
}
bool IDVDestination::Cleanup()
{
	return true;
}

